/**
 * Created by wzh on 2016/6/29.
 */
'use strict'
swan_pc
    .controller('CompanyController',function($scope,$rootScope,$state,$timeout,$filter,CompanyInfo,$q,ngDialog){
        $scope.companyInfos;
        $scope.sortedCompanyInfos=[];
        $scope.presentCompanyInfo;
        $scope.dataStruct=[
            {
                name:"基本信息",
                type:"normal",
                blockName:"companyBaseInfo",
                struct:[
                    {
                        name:"公司名称",
                        key: "name",
                        option:1,
                        select:[],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:"",
                    },
                    {
                        name: "公司别名",
                        key: "alias",
                        option:1,
                        select:[],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:"",
                    },
                    {
                        name:"英文名称",
                        key: "englishName",
                        option:1,
                        select:[],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:"",
                    },
                    {
                        name:"公司概况",
                        key: "overview",
                        option:1,
                        select:[],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:"",
                    },
                    {
                        name:"(与我公司)业务关系",
                        key: "businessConnection",
                        option:0,
                        select:[],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:"",
                    },
                    {
                        name:"(与我公司)友好程度",
                        key: "friendship",
                        option:0,
                        select:[],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:"",
                    },
                    {
                        name:"(与我公司)重要程度",
                        key: "importance",
                        option:0,
                        select:[],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:"",
                    },
                    {
                        name:"成立时间",
                        key: "foundDate",
                        option:2,
                        select:[],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:"",
                    },
                    {
                        name:"注册资本",
                        key: "registerCapital",
                        option:1,
                        select:[],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:"",
                    },
                    {
                        name:"公司类型",
                        key: "type",
                        option:1,
                        select:[],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:""
                    },
                    {
                        name:"货币单位",
                        key: "unit",
                        option:1,
                        select:[],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:""
                    },
                    {
                        name:"主页",
                        key: "webSite",
                        option:1,
                        select:[],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:""
                    }
                ]
            },
            {
                name:"个人关系",
                type:"normal",
                blockName:"companyRelationWithMe",
                struct:[
                    {
                        name:"(与我的)商业联系",
                        key: "businessConnectionWithMe",
                        option:3,
                        select:[
                            {
                                name:"客户",
                                value:"客户"
                            },
                            {
                                name:"合作伙伴",
                                value:"合作伙伴"
                            },
                            {
                                name:"竞争对手",
                                value:"竞争对手"
                            },
                            {
                                name:"供应商",
                                value:"供应商"
                            },
                            {
                                name:"其他",
                                value:"其他"
                            }
                        ],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:""
                    },
                    {
                        name:"(与我的)友好程度",
                        key: "friendshipWithMe",
                        option:3,
                        select:[
                            {
                                name:"讨厌",
                                value:"讨厌"
                            },
                            {
                                name:"烦",
                                value:"烦"
                            },
                            {
                                name:"认识",
                                value:"认识"
                            },
                            {
                                name:"接受",
                                value:"接受"
                            },
                            {
                                name:"好感",
                                value:"好感"
                            }
                        ],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:""
                    },
                    {
                        name:"(对我的)重要程度",
                        key: "importanceToMe",
                        option:3,
                        select:[
                            {
                                name:"不需要",
                                value:"不需要"
                            },
                            {
                                name:"需要",
                                value:"需要"
                            },
                            {
                                name:"重要",
                                value:"重要"
                            },
                            {
                                name:"很重要",
                                value:"很重要"
                            },
                            {
                                name:"极其重要",
                                value:"极其重要"
                            }
                        ],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:""
                    }
                ]
            },
            {
                name:"地址列表",
                type:"repeat",
                blockName:"companyAddressList",
                preName:"地址",
                struct:[
                    {
                        name:"三级地址菜单",
                        key: ["province","city","district"],
                        option:4,
                        select:[],
                        show:[],
                        preview:5,
                        preBefore:"",
                        preAfter:"",
                    },
                    {
                        name:"地区",
                        key: "area",
                        option:1,
                        select:[],
                        show:[],
                        preview:2,
                        preBefore:"",
                        preAfter:"",
                    },
                    {
                        name:"街道",
                        key: "street",
                        option:1,
                        select:[],
                        show:[],
                        preview:2,
                        preBefore:"",
                        preAfter:"",
                    },
                    {
                        name:"门牌号",
                        key: "house",
                        option:1,
                        select:[],
                        show:[],
                        preview:3,
                        preBefore:"",
                        preAfter:"号",
                    },
                    {
                        name:"详细地址",
                        key: "detailAddress",
                        option:1,
                        select:[],
                        show:[],
                        preview:1,
                        preBefore:":",
                        preAfter:"",
                    },
                    {
                        name:"邮编",
                        key: "postcode",
                        option:1,
                        select:[],
                        show:[],
                        preview:4,
                        preBefore:"(",
                        preAfter:")"
                    }
                ]
            },
            {
                name:"电话列表",
                type:"repeat",
                blockName:"companyPhoneList",
                preName:"电话",
                struct:[
                    {
                        name:"热线类型",
                        key:"lineName",
                        option:3,
                        select:[
                            {
                                name:"默认",
                                value:"默认"
                            },
                            {
                                name:"专用",
                                value:"专用"
                            }
                        ],
                        show:[],
                        preview:3,
                        preBefore:"",
                        preAfter:":"
                    },
                    {
                        name:"热线号码",
                        key:"lineNumber",
                        option:1,
                        show:[],
                        preview:2,
                        preBefore:"",
                        preAfter:""
                    }
                ]
            },
            {
                name:"部门信息",
                type:"recursion",
                blockName:"companyDepartmentInfo",
                struct:[
                    {
                        name:"部门名称",
                        key: "name",
                        option:1,
                        select:[],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:"",
                    },
                    {
                        name:"职责",
                        key: "duty",
                        option:1,
                        select:[],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:"",
                    }
                ]
            }
        ]

        //init
        $scope.init=function(){

        }
        $scope.dirty={
            companyBaseInfo:false,
            companyRelationWithMe:false,
            companyAddressList:false,
            companyPhoneList:false,
            companyDepartmentInfo:false
        }
        $scope.initDirty=function() {
            $rootScope.companyDirty = false;
            $scope.dirty.companyBaseInfo=false;
            $scope.dirty.companyRelationWithMe=false;
            $scope.dirty.companyAddressList=false;
            $scope.dirty.companyPhoneList=false;
            $scope.dirty.companyDepartmentInfo=false;
        }
        $scope.showBackButton=function(){
            return $rootScope.toState.name!='company'
        }
        //sort
        $scope.compare=function(str1,str2,opt){
            if ((str1==undefined||str1=="")&&(str2==undefined||str2=="")) return 0;
            else if (str1==undefined||str1=="") return 1;
            else if (str2==undefined||str2=="") return -1;
            if (opt==true) return str1.localeCompare(str2);
            else return str2.localeCompare(str1);
        }
        $scope.sortByElement=function(ele,opt){
            for (var i=0;i<$scope.sortedCompanyInfos.length-1;i++){
                var temp=i;
                for (var j=i+1;j<$scope.sortedCompanyInfos.length;j++){
                    if(ele=="name"){
                        if ($scope.compare($scope.sortedCompanyInfos[temp].companyBaseInfo.name,$scope.sortedCompanyInfos[j].companyBaseInfo.name,opt)>0) temp=j;
                    }
                    if(ele=="englishName"){
                        if ($scope.compare($scope.sortedCompanyInfos[temp].companyBaseInfo.englishName,$scope.sortedCompanyInfos[j].companyBaseInfo.englishName,opt)>0) temp=j;
                    }
                    if(ele=="alias"){
                        if ($scope.compare($scope.sortedCompanyInfos[temp].companyBaseInfo.alias,$scope.sortedCompanyInfos[j].companyBaseInfo.alias,opt)>0) temp=j;
                    }
                }
                if (temp!=i){
                    var temporary=$scope.sortedCompanyInfos[temp];
                    $scope.sortedCompanyInfos[temp]=$scope.sortedCompanyInfos[i];
                    $scope.sortedCompanyInfos[i]=temporary;
                }
            }
        }
        $scope.sort=function(array){
            $scope.sortedCompanyInfos=[];
            for (var i=0;i<array.length;i++) {
                $scope.sortedCompanyInfos.push(array[i])
            }
            for (var i=0;i<$scope.sortedCompanyInfos.length;i++){
                if ($scope.sortedCompanyInfos[i].subCompanys.length>0){
                    angular.forEach($scope.sortedCompanyInfos[i].subCompanys,function (data){
                        $scope.sortedCompanyInfos.push(data);
                    })
                }
            }
            $scope.sortByElement("name",true);
        }
        //init
        $scope.updatePresentCompany=function(id){
            CompanyInfo.queryAll({infoid:id},function(result){
                $scope.presentCompanyInfo=result;
                $scope.companyInfoPointer={
                    companyBaseInfo:result.companyBaseInfo,
                    companyRelationWithMe:result,
                    companyAddressList:result.addresss,
                    companyPhoneList:result.lineNumbers,
                    companyDepartmentInfo:result.departments
            }
            });
        }
        $scope.changeCompany=function(id){
            $scope.updatePresentCompany(id);
            $state.go("companydetail");
        }
        $scope.loadAll=function(option){
            CompanyInfo.query({infoid:"all"},function(result){
                $scope.companyInfos=result;
                $scope.sort(result);
                if (option==undefined){
                    if (result.length!=0) $scope.updatePresentCompany($scope.companyInfos[0].id)
                }
            });
        }
        $scope.clear=function(option){
            var parentId=(option!=undefined)?$scope.addCompanyInfo.parentCompanyId:null;
            var top=(option!=undefined)?$scope.addCompanyInfo.companyBaseInfo.isTop:false;
            $scope.addCompanyInfo={
                "addresss": [
                    {
                        "area": "",
                        "city": "",
                        "detailAddress": "",
                        "district": "",
                        "house": "",
                        "postcode": "",
                        "province": "",
                        "street": "",
                    }
                ],
                "businessConnectionWithMe": "",
                "companyBaseInfo": {
                    "alias": "",
                    "businessConnection": "",
                    "englishName": "",
                    "foundDate": "",
                    "friendship": "",
                    "importance": "",
                    "isRelated": false,
                    "isTop": true,
                    "name": "",
                    "overview": "",
                    "registerCapital": 0,
                    "type": "",
                    "unit": "",
                    "webSite": ""
                },
                "departments": [
                    {
                        "duty": "",
                        "name": "",
                        "subDepartments": [
                        ],
                    }
                ],
                "parentCompanyId":parentId,
                "friendshipWithMe": "",
                "importanceToMe": "",
                "lineNumbers": [
                    {
                        "lineName": "",
                        "lineNumber": "",
                    }
                ],
                "subCompanys": [
                    {}
                ],
            }
        }
        $scope.refresh=function(option){
            $scope.loadAll(option);
            $scope.clear();
        }
        $scope.refresh();
        //delete
        $scope.deleteCompany=function(id){
            if(!confirm("确定要删除么?")) return false;
            CompanyInfo.delete({infoid:id},function(result){
                alert("删除成功");
                if(id==$scope.presentCompanyInfo.id) $scope.loadAll();
                else $scope.loadAll(1);
            })
        }
        $scope.back=function(option){
            if($rootScope.toState.name=="companycontactdetail") $rootScope.goSref("companycontact");
            else {
                $scope.refresh(option);
                $rootScope.goSref("company");
            }
        }
        //getCompany
        $scope.getCompanyNameById=function(id){
            var name;
            var searchId;
            searchId=(id==undefined)?$scope.addCompanyInfo.parentCompanyId:id;
            angular.forEach($scope.sortedCompanyInfos,function(data) {
                if (data.id==searchId) name=data.companyBaseInfo.name;
            });
            return name;
        }
        $scope.getCompanyIdByName=function(name){
            var id;
            angular.forEach($scope.sortedCompanyInfos,function(data) {
                if (data.companyBaseInfo.name==name) id=data.id;
            });
            return id;
        }
        $scope.getCompanyInfoById=function(id){
            var info;
            var searchId;
            angular.forEach($scope.sortedCompanyInfos,function(data) {
                if (data.id==id) info=data;
            });
            return info;
        }
        //add
        $scope.addElement=function(array){
            array.push({});
        }
        $scope.addCompany=function(id){
            $scope.clear();
            if (id!=undefined){
                $scope.addCompanyInfo.parentCompanyId=id.toString();
                $scope.addCompanyInfo.companyBaseInfo.isTop=false;
            }
            $state.go("addcompany");
        }
        $scope.changeToTop=function(){
            $scope.addCompanyInfo.parentCompanyId=undefined;
            $scope.addCompanyInfo.companyBaseInfo.isTop=true;
        }
        //update
        $scope.updateCompanyInfo=function(){
            CompanyInfo.update({},$scope.presentCompanyInfo,function(result){
                alert("保存成功！");
                $scope.initDirty();
                $scope.updatePresentCompany(result.id);
            },function(result){
                alert("保存失败！"+result.message);
            })
        }
        $scope.saveCompanyInfo=function(){
            /*if ($scope.addCompanyInfo.parentCompanyId!=""&&$scope.addCompanyInfo.parentCompanyId!=undefined&&$scope.addCompanyInfo.companyBaseInfo.isTop==false){
                $scope.presentCompanyInfo=$scope.getCompanyInfoById($scope.addCompanyInfo.parentCompanyId);
                if($scope.presentCompanyInfo.subCompanys==undefined) $scope.presentCompanyInfo.subCompanys=[];
                $scope.presentCompanyInfo.subCompanys.push($scope.addCompanyInfo);
                $scope.updateCompanyInfo();
                $state.go("companydetail")
            }
            else {*/
                CompanyInfo.save({}, $scope.addCompanyInfo, function (result) {
                    alert("保存成功！");
                    $scope.initDirty();
                    $scope.refresh(1);
                    $scope.changeCompany(result.id);
                }, function (result) {
                    alert("保存失败！" + result.message);
                })
            //}
        }
        $scope.resetCompanyInfo=function(id){
            if($rootScope.companyDirty)
                if(!confirm("有数据未保存，确定要重置么")) return false;
            $scope.updatePresentCompany(id);
            $scope.initDirty();
        }
        //筛选
        $scope.filterInfos={
            name:"",
            businessConnection:{
                kh:false,
                hzhb:false,
                jzds:false,
                gys:false,
                qt:false
            },
            importance:{
                bxy:false,
                xy:false,
                zy:false,
                hzy:false,
                jqzy:false
            }
        };
        $scope.infosFilter=function(item){
            /*if ($scope.filterInfo=="") return true;
            if (item.baseInfo.name.indexOf( $scope.filterInfo)>=0) return true;
            if (item.baseInfo.mobileNumberList==undefined||item.baseInfo.mobileNumberList.length==0) return false;
            if (item.baseInfo.mobileNumberList[0].value.indexOf($scope.filterInfo)>=0) return true;*/
            if (item.companyBaseInfo.name.indexOf( $scope.filterInfos.name)<0&&(item.companyBaseInfo.alias==undefined||item.companyBaseInfo.alias.indexOf( $scope.filterInfos.name)<0)&&(item.companyBaseInfo.englishName==undefined||item.companyBaseInfo.englishName.indexOf( $scope.filterInfos.name)<0)) return false;
            var s=item.companyBaseInfo.businessConnection=="客户"?true:false;
            if(!(!$scope.filterInfos.businessConnection.kh&&!$scope.filterInfos.businessConnection.hzhb&&!$scope.filterInfos.businessConnection.jzds&&!$scope.filterInfos.businessConnection.gys&&!$scope.filterInfos.businessConnection.qt
                ||$scope.filterInfos.businessConnection.kh&&item.companyBaseInfo.businessConnection=="客户"||
                $scope.filterInfos.businessConnection.hzhb&&item.companyBaseInfo.businessConnection=="合作伙伴"||
                $scope.filterInfos.businessConnection.jzds&&item.companyBaseInfo.businessConnection=="竞争对手"||
                $scope.filterInfos.businessConnection.gys&&item.companyBaseInfo.businessConnection=="供应商"||
                $scope.filterInfos.businessConnection.qt&&item.companyBaseInfo.businessConnection=="其他")) return false;
            if(!(!$scope.filterInfos.importance.bxy&&!$scope.filterInfos.importance.xy&&!$scope.filterInfos.importance.zy&&!$scope.filterInfos.importance.hzy&&!$scope.filterInfos.importance.jqzy
                ||$scope.filterInfos.importance.bxy&&item.companyBaseInfo.importance=="不需要"||
                $scope.filterInfos.importance.xy&&item.companyBaseInfo.importance=="需要"||
                $scope.filterInfos.importance.zy&&item.companyBaseInfo.importance=="重要"||
                $scope.filterInfos.importance.hzy&&item.companyBaseInfo.importance=="很重要"||
                $scope.filterInfos.importance.jqzy&&item.companyBaseInfo.importance=="极其重要")) return false;
            return true;
        }
        //department
        $scope.deleteDepartment=function(array,index){
            if(array[index].subDepartments!=undefined&&array[index].subDepartments.length>0)
                if(!confirm("删除此部门会删除所有的下属部门，确定要继续么?")) return;
            var notNull=(array[index].name!=""||array[index].duty!=""||array[index].subDepartments!=undefined&&array[index].subDepartments.length>0);
            array.splice(index,1);
            if(notNull)$scope.dirtySet("companyDepartmentInfo");
        }
        $scope.addDepartment=function(array){
            array.push({
                "duty": "",
                "name": "",
                "subDepartments": [
                ],
            });
        }
        //checkDirty
        $scope.dirtySet=function(index){
            $rootScope.companyDirty=true;
            $scope.dirty[index]=true;
        }
        $scope.dirtyGet=function(index){
            return $scope.dirty[index];
        }
        //Excel 可以直接用 无需读懂原理
        function datenum(v, date1904) {
            if (date1904) {
                v += 1462;
            }
            var epoch = Date.parse(v);
            return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
        }
        function sheet_from_array_of_arrays(data) {
            var ws = {};
            var range = {s: {c: 10000000, r: 10000000}, e: {c: 0, r: 0}};
            for (var R = 0; R !== data.length; ++R) {
                for (var C = 0; C !== data[R].length; ++C) {
                    if (range.s.r > R) {
                        range.s.r = R;
                    }
                    if (range.s.c > C) {
                        range.s.c = C;
                    }
                    if (range.e.r < R) {
                        range.e.r = R;
                    }
                    if (range.e.c < C) {
                        range.e.c = C;
                    }
                    var cell = {v: data[R][C]};
                    if (cell.v === null) {
                        continue;
                    }
                    var cell_ref = XLSX.utils.encode_cell({c: C, r: R});

                    if (typeof cell.v === 'number') {
                        cell.t = 'n';
                    } else if (typeof cell.v === 'boolean') {
                        cell.t = 'b';
                    } else if (cell.v instanceof Date) {
                        cell.t = 'n';
                        cell.z = XLSX.SSF._table[14];
                        cell.v = datenum(cell.v);
                    }
                    else {
                        cell.t = 's';
                    }

                    ws[cell_ref] = cell;
                }
            }
            if (range.s.c < 10000000) {
                ws['!ref'] = XLSX.utils.encode_range(range);
            }
            return ws;
        }
        function Workbook() {
            if (!(this instanceof Workbook)) {
                return new Workbook();
            }
            this.SheetNames = [];
            this.Sheets = {};
        }
        $scope.downExcel = function () {
            var d=$q.defer();
            var p=d.promise;
            var t=[];
            var f=0;
            for(var i=0;i<$scope.sortedCompanyInfos.length;i++){
                CompanyInfo.queryAll({infoid:$scope.sortedCompanyInfos[i].id},function(result){
                    t.push(result);
                    f++;
                    if (f==$scope.sortedCompanyInfos.length) d.resolve(t);
                },function (result) {
                    d.reject("网络连接错误")
                })
            }
            p.then(function(t){
                createExcel(t, '公司.xlsx')
            },function(r){
                alert("导入失败:"+r);
            });
        };
        //recursion analyze
        function reGetDepartment(content,s,p,offset){
            for (var y in p){
                var row=[];
                for (var i=0;i<offset;i++) row.push("")
                for (var x in s){
                    row=row.concat([s[x].name,p[y][s[x].key]]);
                }
                row=row.concat(["子部门数量",p[y].subDepartments.length]);
                content.push(row);
                if (p[y].subDepartments.length>0) reGetDepartment(content,s,p[y].subDepartments,offset+1);
            }
        }
        function getBody(d) {
            var b=[];
            for (var i=0;i<$scope.dataStruct.length;i++){
                var t=$scope.dataStruct[i];
                var length=t.blockName=="companyPhoneList"?d["lineNumbers"].length:t.blockName=="companyAddressList"?d["addresss"].length:t.blockName=="companyDepartmentInfo"?d["departments"].length:0;
                if (t.type=="normal")b.push([t.name]);
                else b.push([t.name,length]);
                var s=t.struct;
                if (t.type=="normal"){
                    var title=[];
                    var content=[];
                    for (var x in s){
                        title.push(s[x].name)
                        var p=t.blockName=="companyBaseInfo"?d[t.blockName]:d;
                        content.push(p[s[x].key]);
                    }
                    b.push(title);
                    b.push(content);
                }
                else if(t.type=="repeat"){
                    var title=[];
                    var content=[];
                    for (var x in s){
                        if(s[x].option==4) {
                            title=title.concat(["省","市","县/区"]);
                        }
                        else title.push(s[x].name)
                        var p=t.blockName=="companyPhoneList"?d["lineNumbers"]:t.blockName=="companyAddressList"?d["addresss"]:d;
                        for (var y in p){
                            if (x==0) content.push([]);
                            if(s[x].option==4) content[y]=content[y].concat([p[y][s[x].key[0]],p[y][s[x].key[1]],p[y][s[x].key[2]]]);
                            else content[y].push(p[y][s[x].key]);
                        }
                    }
                    b.push(title);
                    b=b.concat(content);
                }
                else if(t.type=="recursion"){
                    var content=[];
                    var p=d.departments;
                    for (var y in p){
                        var row=[];
                        for (var x in s){
                            row=row.concat([s[x].name,p[y][s[x].key]]);
                        }
                        row=row.concat(["子部门数量",p[y].subDepartments.length]);
                        content.push(row);
                        if (p[y].subDepartments.length>0) reGetDepartment(content,s,p[y].subDepartments,1);
                    }
                    b=b.concat(content);
                }
                b.push([]);
            }
            return b;
        }
        function getH(body,p,offset){
            for (var i=0;i<p.length;i++){
                var row=[];
                for (var j=0;j<offset;j++) row.push("")
                row.push(p[i].companyBaseInfo.name);
                body.push(row);
                if (p[i].subCompanys.length>0) getH(body,p[i].subCompanys,offset+1);
            }
        }
        function createExcel(data, file_path) {
            var head=["层级关系"];
            var body=[];
            getH(body,$scope.companyInfos,0);
            var wb = new Workbook();
            var array = [head,].concat(body);
            var ws = sheet_from_array_of_arrays(array);
            var ws_name = "层级关系";
            wb.SheetNames.push(ws_name);
            wb.Sheets[ws_name] = ws;
            for (var x in data){
                var head=["公司名称",data[x].companyBaseInfo.name]
                if (!data[x].companyBaseInfo.isTop&&data[x].parentCompanyId>0) head=head.concat(["子公司","上级公司",$scope.getCompanyNameById(data[x].parentCompanyId)])
                else head=head.concat(["顶级公司"]);
                var body=getBody(data[x]);
                var array = [head,].concat(body);
                var ws = sheet_from_array_of_arrays(array);
                var ws_name = data[x].companyBaseInfo.name;
                wb.SheetNames.push(ws_name);
                wb.Sheets[ws_name] = ws;
            }
            var wopts = {bookType: 'xlsx', bookSST: true, type: 'binary'};
            var wbout = XLSX.write(wb, wopts);

            function s2ab(s) {
                var buf = new ArrayBuffer(s.length);
                var view = new Uint8Array(buf);
                for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
                return buf;
            }

            /* the saveAs call downloads a file on the local machine */
            saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), file_path)
        }
        function sheet_to_data(workbook) {
            var result = null;
            $scope.body=[];
            $scope.head=[];
            workbook.SheetNames.forEach(function (sheetName) {
                var json = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], {header: 1, raw: true});
                if (!_.isArray(json) || json.length < 2||sheetName=="层级关系")return;
                $scope.sheethead = json[0];
                $scope.sheetbody = json.slice(1);
                $scope.head.push($scope.sheethead)
                $scope.body.push($scope.sheetbody)
            })
            ngDialog.open({
                templateUrl:"scripts/components/myself/company/dialog/uploadCompanyDialog.html",
                scope:$scope,
                controller:["$scope",function($scope){
                    var df=$q.defer();
                    var pm=df.promise;
                    $scope.solved=0;
                    $scope.check=new Array($scope.body.length);
                    $scope.exist=new Array($scope.body.length);
                    $scope.checkExist=function () {
                        for (var i in $scope.body){
                            for (var y=0;y<$scope.sortedCompanyInfos.length;y++){
                                if ($scope.body[i][2][0]==$scope.sortedCompanyInfos[y].companyBaseInfo.name) $scope.exist[i]=true;
                            }
                        }
                    }
                    $scope.checkExist();
                    $scope.length=0;
                    $scope.pushOrPop=function($index) {
                        if($scope.check[$index]==1){
                            $scope.length++;
                        }
                        else $scope.length--;
                    }
                    $scope.checkAll=function (){
                        for (var i=0;i<$scope.check.length;i++){
                            $scope.check[i]=1;
                        }
                        $scope.length=$scope.check.length;
                    }
                    $scope.unCheckAll=function (){
                        for (var i=0;i<$scope.check.length;i++){
                            $scope.check[i]=0;
                        }
                        $scope.length=0;
                    }
                    $scope.reCheckAll=function(){
                        for (var i=0;i<$scope.check.length;i++){
                            $scope.check[i] = $scope.check[i] ==1?0:1;
                        }
                        $scope.length=$scope.check.length-$scope.length
                    }
                    $scope.checkAllUnexist=function(){
                        for (var i=0;i<$scope.check.length;i++){
                            if(!$scope.exist[i]) {
                                if ($scope.check[i] != 1) {
                                    $scope.check[i] = 1;
                                    $scope.length++;
                                }
                            }
                        }
                    }
                    $scope.uploadDate=function(h,b){
                        $scope.clear();
                        var a=$scope.addCompanyInfo;
                        if (h[2]=="顶级公司"){
                            a.parentCompanyId=null;
                            a.companyBaseInfo.isTop=true;
                        }
                        else {
                            a.parentCompanyId= null;//$scope.getCompanyIdByName(h[4]);
                            a.companyBaseInfo.isTop=true;
                        }
                        var l=0;
                        function getDp(line,p,s,deep){
                            for (var i=0;i<line;i++){
                                l++;
                                p[i]={};
                                var r=1;
                                for (var x in s){
                                    p[i][s[x].key]=b[l][r+deep];
                                    r=r+2;
                                }
                                if (b[l][r+deep]>0) {
                                    p[i].subDepartments=[];
                                    getDp(b[l][r+deep],p[i].subDepartments,s,deep+1);
                                }
                            }
                        }
                        for (var i=0;i<$scope.dataStruct.length;i++){
                            var t=$scope.dataStruct[i];
                            var s=t.struct;
                            if (t.type=="normal"){
                                l+=2;
                                var r=0;
                                for (var x in s){
                                    var p=t.blockName=="companyBaseInfo"?a[t.blockName]:a;
                                    p[s[x].key]=b[l][r++];
                                }
                                l+=2;
                            }
                            else if(t.type=="repeat"){
                                var line=b[l][1];
                                l++;
                                for (var c=0;c<line;c++) {
                                    var r=0;
                                    l++;
                                    for (var x in s) {
                                        var p = t.blockName == "companyPhoneList" ? a["lineNumbers"] : t.blockName == "companyAddressList" ? a["addresss"] : a;
                                        if (x==0) p[c]={}
                                        if (s[x].option == 4) {
                                            p[c][s[x].key[0]]=b[l][r++];
                                            p[c][s[x].key[1]]=b[l][r++];
                                            p[c][s[x].key[2]]=b[l][r++];
                                        }
                                        else p[c][s[x].key]=b[l][r++];
                                    }
                                }
                                l+=2;
                            }
                            else if(t.type=="recursion"){
                                var line=b[l][1];
                                var p=a.departments;
                                getDp(line,p,s,0)
                            }
                        }
                        CompanyInfo.save({},a, function(result){
                            $scope.solved++;
                            if($scope.solved==$scope.length) df.resolve($scope.solved);
                        }, function(result){
                            df.reject(result.message);
                        })
                    }
                    $scope.submitImport=function() {
                        if (!confirm("确定要导入这"+$scope.length+"个公司么,已存在的公司会被替换")){ngDialog.closeAll();return;}
                        for (var i in $scope.body){
                            if ($scope.check[i]==1) {
                                if ($scope.exist[i]) {
                                    CompanyInfo.delete({infoid:$scope.getCompanyIdByName($scope.body[i][2][0])},function(){
                                        $scope.uploadDate($scope.head[i],$scope.body[i]);
                                    },function(){
                                        df.reject(result.message);
                                    })
                                }
                                else $scope.uploadDate($scope.head[i],$scope.body[i]);
                            }
                        }
                        pm.then(function(data){
                            alert("成功导入"+data+"个公司");
                            $scope.loadAll(1);
                        },function(reason){
                            alert("导入失败:"+reason)
                        })
                        ngDialog.closeAll();
                    }
                }]
            })
        }
        $scope.upExcel = function (file) {
            if(!file)return;
            var reader = new FileReader();
            var name = file.name;
            reader.onload = function (e) {
                var data = e.target.result;

                var workbook = XLSX.read(data, {type: 'binary'});
                var array=sheet_to_data(workbook);
                /* DO SOMETHING WITH workbook HERE */
            };
            reader.readAsBinaryString(file);
        };
    })